# -*- encoding: utf-8 -*-
"""
@Project : publicOpinionAnalysis 
@FileName: safe_request
@Time    : 2020/4/16 14:40
@Author  : chenych
@Desc    :
"""

import requests
from requests.adapters import HTTPAdapter
import time


class SafeRequest(object):

    def __init__(self):
        self.header =  {'Content-type': 'application/json'}

        self.connect_timeout = 30
        self.read_timeout = 30
        self.retry_time = 3
        self.retry_wait_secs = 1

        self.debug = True

    def debug_log(self, msg):
        if self.debug:
            print(msg)

    def disable_requests_warn(self):
        requests.packages.urllib3.disable_warnings()

    def get(self, t_url, verify=True):
        try:
            r_data = None
            s = requests.session()
            s.mount('http://', HTTPAdapter(max_retries=3))
            s.mount('https://', HTTPAdapter(max_retries=3))

            for i in range(self.retry_time):
                try:
                    r_data = s.get(t_url, headers=self.header,
                                   timeout=(self.connect_timeout, self.read_timeout),
                                   verify=verify)
                    break

                except Exception as e:
                    print(e)
                    if i < self.retry_time - 1:
                        self.debug_log('=== [%s] 第%s次请求失败，重建连接' % (t_url, i + 1))
                        if self.retry_wait_secs is not None and self.retry_wait_secs > 0:
                            time.sleep(self.retry_wait_secs)
                    else:
                        self.debug_log('=== [%s] 第%s次请求失败，放弃请求' % (t_url, i + 1))
                        # self.failed_list.append(t_url)
                        return None
                    continue

            return r_data

        finally:
            s.close()

    def post(self, url, body, verify=True):
        try:
            r_data = None
            s = requests.session()
            s.mount('http://', HTTPAdapter(max_retries=3))
            s.mount('https://', HTTPAdapter(max_retries=3))

            for i in range(self.retry_time):
                try:
                    r_data = s.post(url,
                                    data=body,
                                    headers=self.header,
                                    timeout=(self.connect_timeout, self.read_timeout),
                                    verify=verify)

                    r_data = r_data.text

                    break

                except Exception as e:
                    print(e)
                    if i < self.retry_time - 1:
                        self.debug_log('=== [%s] 第%s次请求失败，重建连接' % (url, i + 1))
                        if self.retry_wait_secs is not None and self.retry_wait_secs > 0:
                            time.sleep(self.retry_wait_secs)
                    else:
                        self.debug_log('=== [%s] 第%s次请求失败，放弃请求' % (url, i + 1))
                        # self.failed_list.append(t_url)
                        return None
                    continue

            return r_data

        finally:
            s.close()


if __name__ == '__main__':
    sr = SafeRequest()
    t_url='http://127.0.0.1:5999/test'
    post_data = {'h1':'cyc', 'h2':'hello'}
    import json
    r = sr.post_data(t_url, json.dumps(post_data))
    print(r)
    print(r.status_code)
    print(r.text)

